//
//  RCOrderVC.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-7-16.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCOrderVC.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"
#import "AppDelegate.h"
#import "RCFeedbackDataModel.h"
#import "GloableEngineService.h"
#import "IManager+ModuleCommitActivity.h"


#define kTagNameText        101
#define kTagPhoneText       102
#define kTagExtraText       103

#define kTextBGImageFile             @"image_about_textBG.png"
#define kFeedBackHolderString        @"请您填写预订时间，就餐或入住人数等"
#define kOrderImageFile              @"login_btn.png"

@interface RCOrderVC ()

@property(nonatomic,retain) UITextField *nameTextView;
@property(nonatomic,retain) UITextField *phoneTextView;
@property(nonatomic,retain) UITextView *extraInfoTextView;
@property(nonatomic,retain) UIButton *orderButton;
@property(nonatomic,retain) UILabel *nameLabel;
@property(nonatomic,retain) UILabel *phoneLabel;
@property(nonatomic,retain) UILabel *extraLabel;
@property(nonatomic,assign) int64_t requestID;
@property(nonatomic,retain) NSString *shopID;
@property(nonatomic,retain) MBProgressHUDEx *progressHub;

@end

@implementation RCOrderVC

@synthesize nameTextView = _nameTextView;
@synthesize nameLabel = _nameLabel;
@synthesize extraInfoTextView = _extraInfoTextView;
@synthesize extraLabel = _extraLabel;
@synthesize phoneTextView = _phoneTextView;
@synthesize phoneLabel = _phoneLabel;
@synthesize orderButton = _orderButton;
@synthesize requestID = _requestID;
@synthesize shopID = _shopID;
@synthesize progressHub = _progressHub;
@synthesize pageType = _pageType;
@synthesize activityID = _activityID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithShopID:(NSString *)shopid{
    self = [super init];
    if (self) {
        self.shopID = shopid;
        self.pageType = OrderPageTypeMerchant;
    }
    return self;
}

-(void)dealloc{
    self.nameTextView = nil;
    self.nameLabel = nil;
    self.extraInfoTextView = nil;
    self.extraLabel = nil;
    self.phoneTextView = nil;
    self.phoneLabel = nil;
    self.orderButton = nil;
    self.shopID = nil;
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.activityID = nil;
    [super dealloc];
}

-(void)loadView{
    [super loadView];
    self.titleLabelText = @"预订";
    self.navigationItem.titleView = [self createTitleView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString *resourcePath = [[NSBundle mainBundle]resourcePath];
    NSString *textBGFilePath = [resourcePath stringByAppendingPathComponent:kTextBGImageFile];
    UIImage *textBGImage = [UIImage imageWithContentsOfFile:textBGFilePath];
    textBGImage = [textBGImage resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    
    _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(14, 29, 36, 16)];
    _nameLabel.backgroundColor = [UIColor clearColor];
    _nameLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    _nameLabel.textColor = [UIColor colorWithHex:0xff505050];
    _nameLabel.text = @"姓名";
    [self.viewContainer addSubview:_nameLabel];
    
    UIImageView *nameImageView = [[UIImageView alloc]initWithFrame:CGRectMake(55, 20, 251, 33)];
    nameImageView.backgroundColor = [UIColor clearColor];
    [nameImageView setImage:textBGImage];
    [self.viewContainer addSubview:nameImageView];
    [nameImageView release];
    
    _nameTextView = [[UITextField alloc]initWithFrame:CGRectMake(58, 21, 245, 31)];
    _nameTextView.tag = kTagNameText;
    _nameTextView.borderStyle = UITextBorderStyleNone;
    _nameTextView.delegate = self;
    _nameTextView.font = [UIFont fontWithName:kFontNameLightHeiti size:14];
    _nameTextView.textAlignment = UITextAlignmentLeft;
    _nameTextView.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _nameTextView.clearButtonMode = UITextFieldViewModeWhileEditing;
    _nameTextView.autocorrectionType = UITextAutocorrectionTypeNo;
    _nameTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _nameTextView.returnKeyType = UIReturnKeyDone;
    [self.viewContainer addSubview:_nameTextView];
    
    _phoneLabel = [[UILabel alloc]initWithFrame:CGRectMake(14, 77, 36, 16)];
    _phoneLabel.backgroundColor = [UIColor clearColor];
    _phoneLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    _phoneLabel.textColor = [UIColor colorWithHex:0xff505050];
    _phoneLabel.text = @"电话";
    [self.viewContainer addSubview:_phoneLabel];
    
    UIImageView *phoneImageView = [[UIImageView alloc]initWithFrame:CGRectMake(55, 68, 251, 33)];
    phoneImageView.backgroundColor = [UIColor clearColor];
    [phoneImageView setImage:textBGImage];
    [self.viewContainer addSubview:phoneImageView];
    [phoneImageView release];
    
    _phoneTextView = [[UITextField alloc]initWithFrame:CGRectMake(58, 69, 245, 31)];
    _phoneTextView.tag = kTagPhoneText;
    _phoneTextView.borderStyle = UITextBorderStyleNone;
    _phoneTextView.delegate = self;
    _phoneTextView.placeholder = @"必填";
    _phoneTextView.font = [UIFont fontWithName:kFontNameHelvetica size:14];
    _phoneTextView.textAlignment = UITextAlignmentLeft;
    _phoneTextView.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _phoneTextView.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phoneTextView.autocorrectionType = UITextAutocorrectionTypeNo;
    _phoneTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _phoneTextView.returnKeyType = UIReturnKeyDone;
    [self.viewContainer addSubview:_phoneTextView];

    
    _extraLabel = [[UILabel alloc]initWithFrame:CGRectMake(14, 125, 36, 16)];
    _extraLabel.backgroundColor = [UIColor clearColor];
    _extraLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    _extraLabel.textColor = [UIColor colorWithHex:0xff505050];
    _extraLabel.text = @"备注";
    [self.viewContainer addSubview:_phoneLabel];
    
    UIImageView *extraImageView = [[UIImageView alloc]initWithFrame:CGRectMake(55, 116, 251, 181)];
    extraImageView.backgroundColor = [UIColor clearColor];
    [extraImageView setImage:textBGImage];
    [self.viewContainer addSubview:extraImageView];
    [extraImageView release];
    
    _extraInfoTextView = [[UITextView alloc]initWithFrame:CGRectMake(58, 117, 245, 179)];
    _extraInfoTextView.tag = kTagExtraText;
    _extraInfoTextView.backgroundColor = [UIColor clearColor];
    _extraInfoTextView.delegate = self;
    _extraInfoTextView.textColor = [UIColor colorWithHex:0xff979797];
    _extraInfoTextView.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
    [_extraInfoTextView setReturnKeyType:UIReturnKeyDone];
    _extraInfoTextView.text = kFeedBackHolderString;
    [self.viewContainer addSubview:_extraInfoTextView];
    
    _orderButton = [[UIButton alloc]initWithFrame:CGRectMake(55, 314, 251, 35)];
    _orderButton.backgroundColor = [UIColor clearColor];
    NSString *orderPath = [resourcePath stringByAppendingPathComponent:kOrderImageFile];
    [_orderButton setBackgroundImage:[UIImage imageWithContentsOfFile:orderPath] forState:UIControlStateNormal];
    [_orderButton setBackgroundImage:[UIImage imageWithContentsOfFile:orderPath] forState:UIControlStateHighlighted];
    [_orderButton addTarget:self action:@selector(orderButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *orderLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 251, 16)];
    orderLabel.backgroundColor = [UIColor clearColor];
    orderLabel.textColor = [UIColor whiteColor];
    orderLabel.textAlignment = UITextAlignmentCenter;
    orderLabel.font = [UIFont fontWithName:kFontNameHeiti size:16];
    orderLabel.shadowColor = [UIColor colorWithHex:0xffc2c2c2];
    orderLabel.shadowOffset = CGSizeMake(0, 0.5);
    orderLabel.text = @"预订";
    [_orderButton addSubview:orderLabel];
    [orderLabel release];
    
    [self.viewContainer addSubview:_orderButton];
}


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if ([textView.text isEqualToString:kFeedBackHolderString] ) {
        textView.text=@"";
    }

    return YES;
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    int length = 0;
    length = [textView.text length];
    if (length > 300) {
        return NO;
    }
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        
        textView.text = kFeedBackHolderString;
    }
}

#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    return YES;
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }else if ([textField.text length] > 20){
        return NO;
    }
    return YES;
}



#pragma order button click
-(void)orderButtonClicked{
    NetworkStatus status = [GloableEngineService sharedInstance].netWorkStatus;
    if (status == kNotReachable) {
        [RCAppDelegate alertWithNetworkError];
        return;
    }
    _orderButton.enabled = NO;
    if (![_phoneTextView.text isEqualToString:@""] && _phoneTextView.text != nil) {
        NSError * error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^1[34578]\\d{9}$" options:0 error:&error];
        NSTextCheckingResult * result = [regex firstMatchInString:_phoneTextView.text options:0 range:NSMakeRange(0, [_phoneTextView.text length])];
        if (!result || (regex.numberOfCaptureGroups + 1) != result.numberOfRanges) {
            [RCAppDelegate alertWithCustomizeString:@"手机号码输入格式错误哦！"];
            _orderButton.enabled = YES;
            return;
        }
    }else{
        [RCAppDelegate alertWithCustomizeString:@"手机号码不能为空哦！"];
        _orderButton.enabled = YES;
        return;
    }
    [self requestData];
}

-(void)requestData{
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"加载中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    NSString *name = _nameTextView.text;
    NSString *phone = _phoneTextView.text;
    NSString *extra = @"";
    if (![_extraInfoTextView.text isEqualToString:kFeedBackHolderString]) {
        extra = _extraInfoTextView.text;
    }
    if (self.pageType == OrderPageTypeMerchant) {
        
        _requestID = [[IManager sharedInstance]requestOrder:name withShopID:self.shopID withPhone:phone withExtraInfo:extra withDelegate:self];
    }else{
        _requestID = [[IManager sharedInstance]requestCommitActivity:self.activityID withName:name withContent:extra withPhone:phone withDelegate:self];
    }
    
}

-(void)updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        RCFeedbackDataModel *orderDataModel = (RCFeedbackDataModel *)dataModel;
        if (orderDataModel.errorNO == 0) {
            [RCAppDelegate alertWithCustomizeString:@"预订成功"];
            [self performSelector: @selector(backButtonClicked) withObject: nil afterDelay: 2];
        }else{
            [RCAppDelegate alertWithCustomizeString:@"预订失败"];
            _orderButton.enabled = YES;
        }
    }
}

-(void)updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        [RCAppDelegate alertWithCustomizeString:@"预订失败"];
        _orderButton.enabled = YES;
    }
}

-(void)backButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
